﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using ShkSimulation.core.exceptions;
using ShkSimulation.core.util;

namespace ShkSimulation.core.template.model {

	public record InputConfig {
	
		public readonly static string DataPathPrefix = "data-path.";
		
		public Dictionary<string, string> ResourcePaths { get; set; } = new Dictionary<string, string>();
		
		public Dictionary<string, object> Configs { get; set; } = new Dictionary<string, object>();

		public void SetConfigValue(string key, object value) {
			Configs[key] = value;
		}
		
		public void SetResourceValue(string key, string path) {
			ResourcePaths[key] = path;
		}
		
		public string GetResourceValue(string key) {
			if (!ResourcePaths.ContainsKey(key)) {
				return string.Empty;
			}
			return ResourcePaths[key];
		}

		public T GetConfigValue<T>(string key) {
			// 类型转换
			if (!Configs.ContainsKey(key) || Configs[key] is not T) {
				return default(T);
			}
			try {
				string serializeObject = JsonConvert.SerializeObject(Configs[key]);
				return JsonConvert.DeserializeObject<T>(serializeObject);
			} catch (Exception e) {
				Console.WriteLine(e);
				return default(T);
			}

		}

		public static InputConfig Parse(Dictionary<string, string> resourceAndConfigs) {
			if (resourceAndConfigs == null || resourceAndConfigs.Count == 0) {
				return new InputConfig();
			}
			Dictionary<string, string> resources = new Dictionary<string, string>();
			Dictionary<string, object> configs = new Dictionary<string, object>();
			foreach (var (key, value) in resourceAndConfigs) {
				if (key.StartsWith(DataPathPrefix)) {
					string newKey = key.Replace(DataPathPrefix, string.Empty);
					resources[newKey] = value;
				} else {
					configs[key] = value;
				}
			}
			InputConfig config = new InputConfig();
			config.ResourcePaths = resources;
			config.Configs = configs;
			return config;
		}
		        
		public static InputConfig ResolveConfig(string configPath) {
			if (configPath == null) {
				throw new SimulationInitException("必须包含configPath");
			}
			Dictionary<string, string> allYamlConfig = YamlReader.LoadYamlConfig(configPath);
			return Parse(allYamlConfig);
		}


		public static InputConfig Empty() {
			return new InputConfig();
		}

	}

}